<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="begin">开启定时器</button>
    <button class="stop">停止定时器</button>
    <script>
        var beginBtn = document.querySelector('.begin');
        var stopBtn = document.querySelector('.stop');
        var time = null;
        
        beginBtn.addEventListener('click',function(){
            console.log('开启定时');
            time = window.setInterval(() => {
                console.log('定时器回调方法被执行');
            }, 2000);
        })

        stopBtn.addEventListener('click',function(){
            console.log('停止定时器');
            if (time == null) return;
            window.clearInterval(time);
        })
    </script>
</body>
</html>